package com.example.demos.service.impl;

import com.example.demos.dto.MarketDetailDTO;
import com.example.demos.dto.MarketDetailUpdateDTO;
import com.example.demos.entity.StoreOper;
import com.example.demos.mapper.MarketDetailMapper;
import com.example.demos.service.MarketDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class MarketDetailServiceImpl implements MarketDetailService {

    @Autowired
    private MarketDetailMapper marketDetailMapper;


    @Override
    @Transactional
    public int updateMarketDetailState(BigInteger marketDetailId, BigInteger storeUuid, HttpSession session) {
        MarketDetailUpdateDTO m = marketDetailMapper.queryGoodsIdAndNumAndMarketId(marketDetailId);
        int goodsNum = m.getGoodsNum().intValue();
        BigInteger goodsId = m.getGoodsId();
        BigInteger marketUuid = m.getMarketId();
        //查询库存，如果库存不足则显示
        Integer storeNum = marketDetailMapper.queryStoreNum(goodsId, storeUuid);
        if (storeNum == null) return -2;
        if (storeNum < goodsNum) return -1;
        int update = marketDetailMapper.updateMarketDetailState(
                marketDetailId,
                storeUuid,
                LocalDateTime.now(),
                session.getAttribute("username").toString());
        //库存数量减少
        BigInteger goodsNumParam = new BigInteger(String.valueOf(goodsNum));
        marketDetailMapper.updateStoreDetailNum(goodsId, storeUuid, goodsNumParam);
        //如果全部商品出库，订单也出库
        List<MarketDetailDTO> marketDetailDTOS =
                marketDetailMapper.queryMarketDetailState(marketUuid);
        int count = 0;
        for (int i = 0; i < marketDetailDTOS.size(); i++) {
            if ("1".equals(marketDetailDTOS.get(i).getState())) count++;
        }
        if (count == marketDetailDTOS.size()) marketDetailMapper.updateMarketState(
                marketUuid,
                session.getAttribute("username").toString(),
                LocalDateTime.now());
        //新增库存变更记录
        StoreOper storeOper = new StoreOper();
        BigInteger empId = new BigInteger(session.getAttribute("empId").toString());
        storeOper.setStoreUuid(storeUuid);
        storeOper.setEmpUuid(empId);
        storeOper.setOperTime(LocalDateTime.now());
        storeOper.setGoodsUuid(goodsId);
        storeOper.setNum(m.getGoodsNum());
        storeOper.setType("0");
        marketDetailMapper.insertStoreOper(storeOper);
        return update;
    }
}
